"""
斑马打印机设备实现
==================

该模块实现了基于Socket协议的斑马打印机设备控制接口。
"""

import json
import os
import time
from typing import Any, Dict, List, Optional, Callable, Union,Tuple
from ..utils.json_object import JsonObject
from ..core.communication_interface import CommunicationInterface
from ..core.device_interface import DeviceInterface
from ..readwrite.read_interface import ReadInterface
from ..readwrite.write_interface import WriteInterface
from ..protocols.standard.socket.socket_interface import SocketInterface, CommunicationProtocol
from ..utils.logger import get_logger
from ..utils.json_object import load_json_object,JsonObject
from .printer.generator import ZPrinterGenerator
from .printer.zpl_label_config import ZplLabelError


logger = get_logger("driver.device")

# 定义打印标签类型枚举
from enum import Enum
class PrintLabelType(Enum):
    TEXT = "text"
    BARCODE = "barcode"
    QRCODE = "qrcode"
    GRAPHICS = "graphics"
    IMAGE = "image"

class ZebraPrinterDevice(DeviceInterface):
    """
    斑马打印机设备实现类

    该类实现了基于Socket协议的斑马打印机设备控制接口，提供了斑马打印机设备的连接管理、数据读写、参数配置等常用功能。
    """

    def __init__(self, communication: CommunicationInterface, address_mapping: Union[str, Dict[str, Any], JsonObject, object] = None):
        """
        初始化设备控制接口

        Args:
            communication: 通信接口实例
            address_mapping: 地址映射配置（可选），用于设备地址转换
                           可以是JSON文件路径、字典、JsonObject或其他对象
        """
        try:
            # 而是直接初始化必要的属性
            super().__init__(communication,address_mapping)
            # 安全地访问address_mapping
            address_mapping_data = None
            if hasattr(address_mapping, 'address_mapping'):
                address_mapping_data = address_mapping.address_mapping
            else:
                address_mapping_data = getattr(address_mapping, 'address_mapping', address_mapping)

            # 检查commands是否存在
            if hasattr(address_mapping_data, 'commands'):
                self.commands = address_mapping_data.commands
            else:
                # 如果两个都不存在，则直接使用address_mapping_data
                self.commands = address_mapping_data

            self._plc_info = {}
            self.protocol = CommunicationProtocol.SOCKET

            # 初始化ZPL生成器
            printer_labels_config = None
            if communication is not None and communication.config is not None:
                printer_labels_config = communication.config.get("printer_labels_config") if communication.config.get("printer_labels_config") else None

            self.printer_generator = ZPrinterGenerator(printer_labels_config)  # 初始化ZPL生成器

            if not self.initialize():
                logger.error("斑马打印机设备初始化失败")
                return
            logger.info("斑马打印机设备初始化完成")
            self.communication:SocketInterface = communication  # 暂时使用
        except Exception as e:
            logger.error(f"斑马打印机设备初始化异常: {e}")
            raise

    # 添加打印接口,统一打印接口
    def print(self, label_type: PrintLabelType, label_id: str, data: Union[str, List[str]] = None, **kwargs) -> bool:
        """
        打印标签

        Args:
            label_type: 标签类型,使用PrintLabelType枚举
            label_id: 标签ID
            data: 标签数据（可选）,使用配置文件默认数据
            **kwargs: 其他参数,如打印参数
              - confirm_print：确认打印: bool,默认False
              - confirm_print_timeout：确认打印超时时间: int,默认10
              - print_count：打印数量: int,默认1

        Returns:
            bool: 打印是否成功

        Raises:
            TypeError: 当参数类型不正确时抛出
            ValueError: 当参数值不合法时抛出
        """
        if not isinstance(label_type, PrintLabelType):
            raise TypeError("label_type必须是PrintLabelType枚举类型")

        if not isinstance(label_id, str):
            raise TypeError("label_id必须是字符串类型")

        if not label_id:
            raise ValueError("label_id不能为空")

        try:
            # 生成ZPL代码
            if label_type == PrintLabelType.TEXT:
                print_result = self.print_text(label_id, data, **kwargs)
            elif label_type == PrintLabelType.BARCODE:
                print_result = self.print_barcode(label_id, data, **kwargs)
            elif label_type == PrintLabelType.QRCODE:
                print_result = self.print_qrcode(label_id, data, **kwargs)
            elif label_type == PrintLabelType.GRAPHICS:
                print_result = self.print_graphics(label_id, data, **kwargs)
            elif label_type == PrintLabelType.IMAGE:
                print_result = self.print_image(label_id, data, **kwargs)
            else:
                raise ValueError(f"不支持的标签类型: {label_type}")

            # 发送ZPL代码到打印机
            return print_result
        except Exception as e:
            logger.error(f"打印标签失败: {e}")
            return False

    # 添加打印文本接口
    def print_text(self, label_id: str = "text_label_default", data: Union[str, List[str]] = None, **kwargs) -> bool:
        """
        打印文本

        Args:
            label_id: 标签ID
            data: 标签数据，可为字符串或字符串列表，使用配置文件默认数据
            **kwargs: 其他参数,如打印参数
              - confirm_print：确认打印: bool,默认False
              - confirm_print_timeout：确认打印超时时间: int,默认10
              - print_count：打印数量: int,默认1

        Returns:
            bool: 打印是否成功

        Raises:
            TypeError: 当参数类型不正确时抛出
            ZplLabelError: 当标签生成过程中出现错误时抛出
        """
        if not isinstance(label_id, str):
            raise TypeError("label_id必须是字符串类型")

        if not label_id:
            raise ValueError("label_id不能为空")

        # 获取参数
        confirm_print = kwargs.get("confirm_print", False)
        confirm_print_timeout = kwargs.get("confirm_print_timeout", 10)
        print_count = kwargs.get("print_count", 1)

        try:
            # 支持data为str或List[str]
            if isinstance(data, str):
                data_list = [data]
            else:
                data_list = data
            logger.info(f"打印文本数据: {data_list}")
            # 生成ZPL代码
            zpl_code = self.printer_generator.generate_text_by_id(label_id, data_list)
            if not zpl_code:
                logger.error("无法生成文本标签")
                return False

            # 发送ZPL代码到打印机
            if self.communication:
                # 根据打印数量重复ZPL内容
                if print_count > 1:
                    # 在多份打印时，在ZPL内容前添加打印份数命令
                    zpl_with_count = f"~R{print_count}\n{zpl_code}"
                else:
                    zpl_with_count = zpl_code

                self.communication.send_data(zpl_with_count)
                whileCount = confirm_print_timeout/2

                # 如果需要确认打印，则等待打印机响应或超时
                if confirm_print:
                    try:
                        logger.info("等待打印机确认打印...")
                        while whileCount > 0:
                            time.sleep(2)
                            whileCount -= 1
                            response = self.get_device_status()
                            if response["state"] == "READY":
                                return True
                            logger.info(f"打印机响应: {response}")
                        logger.warning("等待打印机确认时超时,未监测到打印完成状态")
                        return False
                    except Exception as e:
                        logger.warning(f"等待打印机确认时超时或发生错误: {e}")
                        # 即使没有收到确认，如果数据已发送成功，仍返回True
                        return True
                else:
                    return True
            else:
                logger.error("通信接口未初始化")
                return False
        except ZplLabelError as e:
            logger.error(f"生成文本标签失败: {e}")
            return False
        except Exception as e:
            logger.error(f"打印文本失败: {e}")
            return False

    # 添加打印条码接口
    def print_barcode(self, label_id: str = "barcode_label_default", data: Union[str, List[str]] = None, **kwargs) -> bool:

        """
        打印条码

        Args:
            label_id: 标签ID
            data: 标签数据，可为字符串或字符串列表，使用配置文件默认数据
            **kwargs: 其他参数,如打印参数
              - confirm_print：确认打印: bool,默认False
              - confirm_print_timeout：确认打印超时时间: int,默认10
              - print_count：打印数量: int,默认1

        Returns:
            bool: 打印是否成功

        Raises:
            TypeError: 当参数类型不正确时抛出
            ZplLabelError: 当标签生成过程中出现错误时抛出
        """
        if not isinstance(label_id, str):
            raise TypeError("label_id必须是字符串类型")

        if not label_id:
            raise ValueError("label_id不能为空")

        # 获取参数
        confirm_print = kwargs.get("confirm_print", False)
        confirm_print_timeout = kwargs.get("confirm_print_timeout", 10)
        print_count = kwargs.get("print_count", 1)

        try:
            # 支持data为str或List[str]
            if isinstance(data, str):
                data_list = [data]
            else:
                data_list = data

            logger.info(f"打印条码数据: {data_list}")

            # 生成ZPL代码
            zpl_code = self.printer_generator.generate_barcode_by_id(label_id, data_list)

            if not zpl_code:
                logger.error("无法生成条码标签")
                return False

            # 发送ZPL代码到打印机
            if self.communication:
                # 根据打印数量重复ZPL内容
                if print_count > 1:
                    # 在多份打印时，在ZPL内容前添加打印份数命令
                    zpl_with_count = f"~R{print_count}\n{zpl_code}"
                else:
                    zpl_with_count = zpl_code

                self.communication.send_data(zpl_with_count)
                whileCount = confirm_print_timeout/2
                # 如果需要确认打印，则等待打印机响应或超时
                if confirm_print:
                    try:
                        logger.info("等待打印机确认打印...")
                        while whileCount > 0:
                            time.sleep(2)
                            whileCount -= 1
                            response = self.get_device_status()
                            if response["state"] == "READY":
                                return True
                            logger.info(f"打印机响应: {response}")
                        logger.warning("等待打印机确认时超时,未监测到打印完成状态")
                        return False
                    except Exception as e:
                        logger.warning(f"等待打印机确认时超时或发生错误: {e}")
                        # 即使没有收到确认，如果数据已发送成功，仍返回True
                        return True
                else:
                    return True
            else:
                logger.error("通信接口未初始化")
                return False
        except ZplLabelError as e:
            logger.error(f"生成条码标签失败: {e}")
            return False
        except Exception as e:
            logger.error(f"打印条码失败: {e}")
            return False

    # 添加打印二维码接口
    def print_qrcode(self, label_id: str = "qrcode_label_default", data: Union[str, List[str]] = None, **kwargs) -> bool:

        """
        打印二维码

        Args:
            label_id: 标签ID
            data: 标签数据，可为字符串或字符串列表，使用配置文件默认数据
            **kwargs: 其他参数,如打印参数
              - confirm_print：确认打印: bool,默认False
              - confirm_print_timeout：确认打印超时时间: int,默认10
              - print_count：打印数量: int,默认1

        Returns:
            bool: 打印是否成功

        Raises:
            TypeError: 当参数类型不正确时抛出
            ZplLabelError: 当标签生成过程中出现错误时抛出
        """
        if not isinstance(label_id, str):
            raise TypeError("label_id必须是字符串类型")

        if not label_id:
            raise ValueError("label_id不能为空")

        # 获取参数
        confirm_print = kwargs.get("confirm_print", False)
        confirm_print_timeout = kwargs.get("confirm_print_timeout", 10)
        print_count = kwargs.get("print_count", 1)

        try:
            # 支持data为str或List[str]
            if isinstance(data, str):
                data_list = [data]
            else:
                data_list = data

            logger.info(f"打印二维码数据: {data_list}")
            # 生成ZPL代码
            zpl_code = self.printer_generator.generate_qrcode_by_id(label_id, data_list)

            if not zpl_code:
                logger.error("无法生成二维码标签")
                return False

            # 发送ZPL代码到打印机
            if self.communication:
                # 根据打印数量重复ZPL内容
                if print_count > 1:
                    # 在多份打印时，在ZPL内容前添加打印份数命令
                    zpl_with_count = f"~R{print_count}\n{zpl_code}"
                else:
                    zpl_with_count = zpl_code

                self.communication.send_data(zpl_with_count)
                whileCount = confirm_print_timeout/2

                # 如果需要确认打印，则等待打印机响应或超时
                if confirm_print:
                    try:
                        logger.info("等待打印机确认打印...")
                        while whileCount > 0:
                            time.sleep(2)
                            whileCount -= 1
                            response = self.get_device_status()
                            if response["state"] == "READY":
                                return True
                            logger.info(f"打印机响应: {response}")
                        logger.warning("等待打印机确认时超时,未监测到打印完成状态")
                        return False
                    except Exception as e:
                        logger.warning(f"等待打印机确认时超时或发生错误: {e}")
                        # 即使没有收到确认，如果数据已发送成功，仍返回True
                        return True
                else:
                    return True
            else:
                logger.error("通信接口未初始化")
                return False
        except ZplLabelError as e:
            logger.error(f"生成二维码标签失败: {e}")
            return False
        except Exception as e:
            logger.error(f"打印二维码失败: {e}")
            return False

    # 添加打印图形接口
    def print_graphics(self, label_id: str = "graphics_label_default", data: Union[str, List[str]] = None, **kwargs) -> bool:
        """
        打印图形

        Args:
            label_id: 标签ID
            data: 标签数据，可为字符串或字符串列表，使用配置文件默认数据
            **kwargs: 其他参数,如打印参数
              - confirm_print：确认打印: bool,默认False
              - confirm_print_timeout：确认打印超时时间: int,默认10
              - print_count：打印数量: int,默认1

        Returns:
            bool: 打印是否成功

        Raises:
            TypeError: 当参数类型不正确时抛出
            ZplLabelError: 当标签生成过程中出现错误时抛出
        """
        if not isinstance(label_id, str):
            raise TypeError("label_id必须是字符串类型")

        if not label_id:
            raise ValueError("label_id不能为空")

        # 获取参数
        confirm_print = kwargs.get("confirm_print", False)
        confirm_print_timeout = kwargs.get("confirm_print_timeout", 10)
        print_count = kwargs.get("print_count", 1)

        try:
            # 支持data为str或List[str]
            if isinstance(data, str):
                data_list = [data]
            else:
                data_list = data

            logger.info(f"打印图形数据: {data_list}")
            # 生成ZPL代码
            zpl_code = self.printer_generator.generate_graphics_by_id(label_id, data_list)
            if not zpl_code:
                logger.error("无法生成图形标签")
                return False

            # 发送ZPL代码到打印机
            if self.communication:
                # 根据打印数量重复ZPL内容
                if print_count > 1:
                    # 在多份打印时，在ZPL内容前添加打印份数命令
                    zpl_with_count = f"~R{print_count}\n{zpl_code}"
                else:
                    zpl_with_count = zpl_code

                self.communication.send_data(zpl_with_count)

                # 如果需要确认打印，则等待打印机响应或超时
                if confirm_print:
                    try:
                        response = self.communication.receive_data(timeout=confirm_print_timeout)
                        logger.info(f"打印机响应: {response}")
                        return True
                    except Exception as e:
                        logger.warning(f"等待打印机确认时超时或发生错误: {e}")
                        # 即使没有收到确认，如果数据已发送成功，仍返回True
                        return True
                else:
                    return True
            else:
                logger.error("通信接口未初始化")
                return False
        except ZplLabelError as e:
            logger.error(f"生成图形标签失败: {e}")
            return False
        except Exception as e:
            logger.error(f"打印图形失败: {e}")
            return False

    # 添加打印图片接口
    def print_image(self, label_id: str="image_label_default", data: Union[str, List[str]]=None) -> bool:
        """
        打印图片

        Args:
            label_id: 标签ID
            data: 标签数据，可为字符串或字符串列表，使用配置文件默认数据

        Returns:
            bool: 打印是否成功

        Raises:
            NotImplementedError: 方法尚未实现
        """
        raise NotImplementedError("print_image方法尚未实现")

    def print_raw_zpl(self, zpl_content: str, **kwargs) -> bool:
        """
        直接发送ZPL内容到打印机（新增功能，满足用户可以直接发送PRN文件内容到打印机的需求）

        Args:
            zpl_content (str): ZPL标签内容
            **kwargs: 其他参数,如打印参数
              - confirm_print：确认打印: bool,默认False
              - confirm_print_timeout：确认打印超时时间: int,默认10
              - print_count：打印数量: int,默认1

        Returns:
            bool: 发送是否成功

        Raises:
            TypeError: 当参数类型不正确时抛出
        """
        if not isinstance(zpl_content, str):
            raise TypeError("zpl_content必须是字符串类型")

        if not zpl_content:
            logger.warning("ZPL内容为空")
            return False

        # 获取参数
        confirm_print = kwargs.get("confirm_print", False)
        confirm_print_timeout = kwargs.get("confirm_print_timeout", 10)
        print_count = kwargs.get("print_count", 1)

        # 类型检查
        if not isinstance(confirm_print, bool):
            raise TypeError("confirm_print必须是布尔类型")

        if not isinstance(confirm_print_timeout, (int, float)) or confirm_print_timeout <= 0:
            raise TypeError("confirm_print_timeout必须是正数")

        if not isinstance(print_count, int) or print_count <= 0:
            raise TypeError("print_count必须是正整数")

        try:
            # 根据打印数量重复ZPL内容
            if print_count > 1:
                # 在多份打印时，在ZPL内容前添加打印份数命令
                zpl_with_count = f"~R{print_count}\n{zpl_content}"
            else:
                zpl_with_count = zpl_content

            # 发送ZPL代码到打印机
            if self.communication:
                self.communication.send_data(zpl_with_count)

                # 如果需要确认打印，则等待打印机响应或超时
                if confirm_print:
                    try:
                        response = self.communication.receive_data(timeout=confirm_print_timeout)
                        logger.info(f"打印机响应: {response}")
                        return True
                    except Exception as e:
                        logger.warning(f"等待打印机确认时超时或发生错误: {e}")
                        # 即使没有收到确认，如果数据已发送成功，仍返回True
                        return True
                else:
                    return True
            else:
                logger.error("通信接口未初始化")
                return False
        except Exception as e:
            logger.error(f"发送ZPL内容失败: {e}")
            return False

    # 0. 设备初始化
    def initialize(self) -> bool:
        """
        初始化设备

        Returns:
            bool: 初始化是否成功
        """
        try:
           # 连接设备
        #    return self.connect()
            return True
        except Exception as e:
            logger.error(f"初始化PLC设备失败: {e}")
            return False


    # 2. 设备状态监控
    def get_device_status(self) -> Dict[str, Any]:
        """
        封装打印机状态查询接口

        Returns:
            Dict[str, Any]: 格式为 {state: ***, msg: ***} 的状态信息
                - state: 设备状态 (如 "READY", "BUSY", "PRINTING", "ERROR", "UNKNOWN","ERROR_EXTENSION")
                - msg: 状态相关的信息，包括提示/报警/错误信息
        """
        try:
            # 获取设备状态（假设返回的是 ~HS 响应，包含 STX/ETX 的多行）
            raw_response = self.communication.execute_command(self.commands._device_status.command)
            parsed_status = self._parse_zebra_status(raw_response)

            # 状态映射
            status_map = {
                "就绪": "READY",
                "打印中": "PRINTING",
                "缺纸": "ERROR",
                "打印头打开": "ERROR",
                "已暂停": "BUSY",
                "碳带用尽": "ERROR",
                "通信错误": "ERROR",
                "温度异常": "ERROR",
                "错误": "ERROR",
            }

            state = status_map.get(parsed_status["status"], "UNKNOWN")
            msg = parsed_status["description"]

            return {
                "state": state,
                "msg": msg
            }

        except Exception as e:
            logger.error(f"获取斑马打印机状态信息失败: {e}")
            return {
                "state": "ERROR_EXTENSION",
                "msg": f"获取状态失败: {str(e)}"
            }

    def _parse_zebra_status(self, response: str) -> dict:
        """
        解析斑马打印机 ~HS 指令返回的状态（三行 STX/ETX 包裹的 CSV 格式）

        支持格式：
        <STX>030,0,1,0348,000,0,0,0,000,0,0,0<ETX><CR><LF>
        <STX>001,0,0,0,1,2,4,0,00000000,1,000<ETX><CR><LF>
        <STX>0000,0<ETX><CR><LF>

        Returns:
            {
                "status": "就绪",
                "is_ready": True,
                "description": "打印机正常，可打印。"
            }
        """
        response = response.strip()
        import re
        # 提取所有 STX (\x02) 到 ETX (\x03) 的内容
        if '\x02' in response and '\x03' in response:
            packets = re.findall(r'\x02(.*?)\x03', response)
            if len(packets) < 3:
                return {
                    "status": "未知",
                    "is_ready": False,
                    "description": "响应不完整：未收到三行状态数据"
                }
            lines = [p.strip() for p in packets[:3]]
        else:
            # 回退：尝试按行分割（用于测试）
            lines = [line.strip() for line in response.splitlines() if line.strip()]
            if len(lines) < 3:
                return {
                    "status": "未知",
                    "is_ready": False,
                    "description": "响应格式错误：需要三行数据"
                }

        try:
            # === 解析第一行：String 1 ===
            line1 = [x.strip() for x in lines[0].split(',')]
            if len(line1) < 12:
                raise ValueError("第一行字段不足")

            # b: 缺纸标志 (1 = paper out)
            paper_out = int(line1[1]) == 1
            # c: 暂停标志 (1 = pause active)
            paused = int(line1[2]) == 1
            # j: corrupt RAM
            corrupt_ram = int(line1[9]) == 1
            # k: under temperature
            under_temp = int(line1[10]) == 1
            # l: over temperature
            over_temp = int(line1[11]) == 1

            # === 解析第二行：String 2 ===
            line2 = [x.strip() for x in lines[1].split(',')]
            if len(line2) < 11:
                raise ValueError("第二行字段不足")

            # o: head up flag (1 = head up)
            head_up = int(line2[2]) == 1
            # p: ribbon out flag (1 = ribbon out)
            ribbon_out = int(line2[3]) == 1

            # === 综合状态判断（优先级从高到低）===
            if head_up:
                return {
                    "status": "打印头打开",
                    "is_ready": False,
                    "description": "打印头未关闭，请合上打印头盖后再操作。"
                }

            if paper_out:
                return {
                    "status": "缺纸",
                    "is_ready": False,
                    "description": "打印机缺纸或标签用尽，请装入标签纸后重试。"
                }

            if ribbon_out:
                return {
                    "status": "碳带用尽",
                    "is_ready": False,
                    "description": "热转印碳带用尽，请安装新碳带。"
                }

            if paused:
                return {
                    "status": "已暂停",
                    "is_ready": False,
                    "description": "打印机处于暂停状态，请通过面板或指令取消暂停。"
                }

            if corrupt_ram:
                return {
                    "status": "错误",
                    "is_ready": False,
                    "description": "打印机配置数据丢失（RAM 损坏），请重启并重新配置。"
                }

            if under_temp or over_temp:
                temp_status = "温度过低" if under_temp else "温度过高"
                return {
                    "status": "温度异常",
                    "is_ready": False,
                    "description": f"打印机{temp_status}，无法正常打印，请检查环境温度或打印头。"
                }

            # 所有状态正常
            return {
                "status": "就绪",
                "is_ready": True,
                "description": "打印机状态正常，可接收打印任务。"
            }

        except Exception as e:
            logger.debug(f"解析 ~HS 状态失败: {e}")
            return {
                "status": "未知",
                "is_ready": False,
                "description": "解析打印机状态失败，响应格式异常。"
            }

    def get_device_info(self) -> Dict[str, Any]:
        """
        获取设备基本信息

        Returns:
            Dict[str, Any]: 设备基本信息
        """
        return self.communication.get_device_info()

    # 4. 设备控制命令
    def start(self) -> bool:
        """
        启动设备,即执行打印标签命令

        Returns:
            bool: 操作是否成功
        """
        try:
            return self.communication.send_data(self.commands._print_label.command)
        except Exception as e:
            logger.error(f"启动斑马打印机设备失败: {e}")
            return False

    def stop(self) -> bool:
        """
        停止设备,不支持
        因为斑马打印机不支持停止打印

        Returns:
            bool: 操作是否成功
        """
        return False

    def pause(self) -> bool:
        """
        暂停设备

        Returns:
            bool: 操作是否成功
        """
        try:
            return self.communication.send_data(self.commands._pause.command)
        except Exception as e:
            logger.error(f"暂停斑马打印机设备失败: {e}")
            return False

    def resume(self) -> bool:
        """
        恢复设备,从暂停中恢复

        Returns:
            bool: 操作是否成功
        """
        try:
            return self.communication.send_data(self.commands._resume.command)
        except Exception as e:
            logger.error(f"恢复斑马打印机设备失败: {e}")
            return False

    def reset(self) -> bool:
        """
        复位设备

        Returns:
            bool: 操作是否成功
        """
        try:
            return self.communication.send_data(self.commands._reset.command)
        except Exception as e:
            logger.error(f"复位斑马打印机设备失败: {e}")
            return False

    def emergency_stop(self) -> bool:
        """
        紧急停止

        Returns:
            bool: 操作是否成功
        """
        try:
            return self.communication.send_data(self.commands._emergency_stop.command)
        except Exception as e:
            logger.error(f"紧急停止斑马打印机设备失败: {e}")
            return False

    def test_communication(self) -> bool:
        """
        测试通信

        Returns:
            bool: 通信是否正常
        """
        try:
            return self.communication.send_data(self.commands._test_communication.command)
        except Exception as e:
            logger.error(f"测试通信失败: {e}")
            return False

    # 20. 系统管理
    def reboot(self) -> bool:
        """
        重启设备

        Returns:
            bool: 操作是否成功
        """
        try:
            return self.communication.send_data(self.commands._reboot.command)
        except Exception as e:
            logger.error(f"重启斑马打印机设备失败: {e}")
            return False

